package com.yanqu.road.web.controller.chargecenter;

import com.alibaba.fastjson.JSONObject;
import com.yanqu.road.server.manger.WhiteIpMgr;
import com.yanqu.road.server.su.ReloadManager;
import com.yanqu.road.web.WebServer;
import com.yanqu.road.web.util.IpAddressHelper;
import com.yanqu.road.webservice.invoke.GameWebServiceInvoke;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

@WebServlet(urlPatterns = "/reloadMgr")
public class ReloadMgrServlet extends HttpServlet {

    private static Logger logger = LogManager.getLogger(ReloadMgrServlet.class.getName());

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        JSONObject resultObj = new JSONObject();
        String param1 = null;
        JSONObject jsonObject1;
        try {
            //校验访问IP
            String ip = IpAddressHelper.getIpAddr(request);
            String param = request.getParameter("param");
            JSONObject jsonObject = JSONObject.parseObject(param);
            param1 = jsonObject.getString("param");
            jsonObject1 = JSONObject.parseObject(param1);
            String mgrName = jsonObject1.getString("name");
            if(!Objects.equals("WhiteIpMgr", mgrName)){//刷新白名单的不校验
                if(!WhiteIpMgr.isConsoleWhiteIp(ip)){
                    resultObj.put("status", -10);        //访问IP非法
                    sendMessage(response, resultObj.toString());
                    return;
                }
            }

            logger.info("========ReloadMgrServlet mgrName:{}", mgrName);
            //刷新web本地内存
            ReloadManager reloadManager = new ReloadManager(WebServer.getInstance());
            boolean reloadState = reloadManager.reloadConfig(mgrName);
            try{//如果是刷活动，则刷一下活动商品
                if("ActivityMgr".equals(mgrName)) {
                    reloadManager.reloadConfig("ActivityMallMgr");
                }
            }catch (Exception e){
                logger.info("reload ActivityMgr to reload ActivityMallMgr error:", e);
            }
            boolean gsState = true;

            if (!WebServer.getInstance().isUserCenter()) {//非用户中心
                // 调用 webservice 刷新 gameServer
                JSONObject jsonParam = new JSONObject();
                jsonParam.put("content", mgrName);
                JSONObject gsResult = JSONObject.parseObject(GameWebServiceInvoke.executeAdminOperate("AgentReload|reloadMgr", jsonParam.toJSONString()));
                gsState = 1 == gsResult.getIntValue("status");
            }

            try {
                if (WebServer.getInstance().isUserCenter() && Objects.equals("ServerListMgr", mgrName)) {//用户中心刷新服务器列表时需要刷新AppKey
                    if(!reloadManager.reloadConfig("AppKeyMgr")){
                        logger.info("reload ServerListMgr to reload AppKeyMgr false");
                    }
                }
            }catch (Exception e){
                logger.info("reload ServerListMgr to reload AppKeyMgr error:", e);
            }

            if (reloadState && gsState) {
                resultObj.put("status", 1);
            } else {
                if (!reloadState && !gsState) {
                    // gs web 均失败
                    resultObj.put("status", 0);
                } else if (!reloadState) {
                    // web 失败
                    resultObj.put("status", -1);
                } else {
                    // gs 失败
                    resultObj.put("status", -2);
                }
            }
            sendMessage(response, resultObj.toString());
        } catch (Exception ex) {
            logger.error("param=={}", param1);
            logger.error("GMInterface", ex);
            ex.printStackTrace();
            resultObj.put("status", 0);
            sendMessage(response, resultObj.toString());
        }
    }

    public void sendMessage(HttpServletResponse response, String msg) {

        response.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        response.setHeader("Access-Control-Allow-Origin", "*");
        try {
            response.getWriter().write(msg);
            response.getWriter().flush();
            response.getWriter().close();
        } catch (IOException e) {
            logger.error("", e);
        }
    }
}
